package com.chenc.unitdemo.jwt.golbal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName
 * @Describtion:
 * @Author:Chenc
 * @Date:2024/1/4 14:56
 * @Version 1.0
 */
@RestControllerAdvice
public class GolbalExceptionHandler {


    private static final Logger log = LoggerFactory.getLogger(GolbalExceptionHandler.class);

    public GolbalExceptionHandler() {
    }

    @ResponseBody
    @ExceptionHandler({BusinessException.class})
    public Result handleBusinessException(BusinessException e) {
        if (e.getCodeMsg() != null) {
            return Result.fail(e.getCodeMsg());
        } else {
            log.error(e.getMessage(), e);
            return Result.fail(500, e.getMessage() == null ? "服务器内部错误" : e.getMessage());
        }
    }

    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }

        log.warn(message);
        return Result.fail(400, message);
    }

    @ResponseBody
    @ExceptionHandler({Exception.class})
    public Result exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        String message = "服务器内部错误";
        if (e.getMessage() != null) {
            message = e.getMessage();
        }

        return Result.fail(500, message);
    }


}
